<?php

use think\Session;

/**
 * 通过code请求接口获取openid
 * @param $code 用户登录code
 * @return mixed|string
 */
function getOpenid($code){
    $url = 'https://api.weixin.qq.com/sns/jscode2session';
    $appid = "wx8a376411ca7f6697";
    $secret = "bb1a1cd8f21aa1cbdd8852e0569be332";
    $url .= "?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
    $result = \fast\Http::get($url);
    return json_decode($result,true);
}

/**
 * 获取accessToken
 * @return mixed
 */
function getAccessToken(){
    $url = "https://api.weixin.qq.com/cgi-bin/token";
    $appid = "wx8a376411ca7f6697";
    $secret = "bb1a1cd8f21aa1cbdd8852e0569be332";
    $url .= "?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $result = \fast\Http::get($url);
    return json_decode($result,true);
}
/**
 * 获取公众号accessToken
 * @return mixed
 */
function getWxAccessToken(){
    $WxAccessToken=Session::get('WxAccessToken');
    $time=time();
    if(!empty($WxAccessToken) && strtotime("+2 hour",$WxAccessToken["time"])>$time) return $WxAccessToken;
    $url = "https://api.weixin.qq.com/cgi-bin/token";
    $appid = "wx64d13e22fd555473";
    $secret = "8fa5215c227de9d52eda3c58a79e7a11";
    $url .= "?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $result = \fast\Http::get($url);
    $result =json_decode($result,true);
    $result["time"]=time();
    Session::set('WxAccessToken', $result);
    return $result;
}